import React, { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import {
  Container,
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  Switch,
  FormControlLabel,
  ButtonBase,
} from "@mui/material";

function App() {
  const [processName, setProcessName] = useState("");
  const [pid, setPid] = useState(null); // Initialize with null
  const [baseAddress, setBaseAddress] = useState("");
  const [offset, setOffset] = useState("");
  const [value, setValue] = useState("");
  const [cheats, setCheats] = useState({
    infiniteHealth: false,
    infiniteMoney: false,
    oneHitKill: false,
  });
  const [flash, setFlash] = useState(false); // State to manage flashing effect

  useEffect(() => {
    const unlisten = listen("pid_found", (event) => {
      setPid(event.payload);
    });

    return () => {
      unlisten.then((f) => f());
    };
  }, []);

  useEffect(() => {
    const startMainLoop = async () => {
      try {
        await invoke("thread_main_loop");
        console.log("Main loop started");
      } catch (error) {
        console.error("Failed to start main loop:", error);
      }
    };

    startMainLoop();
  }, []);

  useEffect(() => {
    if (pid !== null) {
      let flashCount = 0;
      const interval = setInterval(() => {
        setFlash((prevFlash) => !prevFlash);
        flashCount += 1;
        if (flashCount >= 10) {
          clearInterval(interval);
          setFlash(false); // Ensure the flash state is reset
        }
      }, 500);

      return () => clearInterval(interval);
    }
  }, []);

  const getProcess = async () => {
    const pids = await invoke("get_process_by_name", { name: processName });
    if (pids.length > 0) {
      setPid(pids[0]);
      const baseAddr = await invoke("get_base_address", { pid: pids[0] });
      setBaseAddress(baseAddr);
    }
  };

  const calculateAddress = () => {
    if (baseAddress && offset) {
      return parseInt(baseAddress, 10) + parseInt(offset, 16);
    }
    return null;
  };

  const writeMemory = async () => {
    const address = calculateAddress();
    if (address !== null) {
      const result = await invoke("write_memory", {
        pid: parseInt(pid),
        address,
        value: parseInt(value),
      });
      alert(result ? "Memory written successfully" : "Failed to write memory");
    } else {
      alert("Invalid address");
    }
  };

  const handleCheatChange = async (name, fnname, enabled) => {
    setCheats((prevCheats) => ({
      ...prevCheats,
      [name]: enabled,
    }));
    // console.log("name=====" + JSON.stringify(name));

    // 调用 Tauri 命令更新后端状态
    await invoke(`set_${fnname}`, { enabled });
  };

  return (
    <Container style={{ padding: "0px" }}>
      <Box display="flex" flexDirection={{ xs: "row", md: "row" }} gap={3} style={{ padding: "16px 16px 16px 16px" }}>
        <Box flex={{ xs: 1, md: 0.5 }} maxWidth="200px">
          <Paper style={{ padding: "16px 16px 16px 16px" }}>
            <Typography variant="h6">修改选项</Typography>
            <Box mb={2}>
              <FormControlLabel
                control={
                  <Switch
                    onClick={() =>
                      handleCheatChange(
                        "infiniteHealth",
                        "infinite_health",
                        !cheats.infiniteHealth
                      )
                    }
                    checked={cheats.infiniteHealth}
                    name="infiniteHealth"
                    color="warning"
                  />
                }
                label="无限血量"
              />
            </Box>
            <Box mb={2}>
              <FormControlLabel
                control={
                  <Switch
                    onClick={() =>
                      handleCheatChange(
                        "infiniteMoney",
                        "infinite_money",
                        !cheats.infiniteMoney
                      )
                    }
                    checked={cheats.infiniteMoney}
                    name="infiniteMoney"
                    color="warning"
                  />
                }
                label="无限金钱"
              />
            </Box>
            <Box mb={2}>
              <FormControlLabel
                control={
                  <Switch
                    onClick={() =>
                      handleCheatChange(
                        "oneHitKill",
                        "one_hit_kill",
                        !cheats.oneHitKill
                      )
                    }
                    checked={cheats.oneHitKill}
                    name="oneHitKill"
                    color="warning"
                  />
                }
                label="一击必杀"
              />
            </Box>
          </Paper>
        </Box>
        <Box flex={{ xs: 1, md: 0.5 }} maxWidth="200px">
          <Paper style={{ padding: 16 }}>
            <Typography style={{ color: "green"}}>游戏信息</Typography>
            <Typography>王国保卫战5 修改器</Typography>
            <Typography>Kingdom Rush 5 Cheat</Typography>
            <Typography style={{ color: "green"}}>程序PID:</Typography>
            <Typography style={{ color: flash ? "red" : "blue" }}>
              {pid !== null ? pid : "NULL"}
            </Typography>
          </Paper>
        </Box>
      </Box>
    </Container>
  );
}

export default App;
